package com.zycfc.zsf.boot.mybatis.typehandler;

import com.zycfc.zsf.boot.data.enums.*;
import java.util.*;
import java.lang.reflect.*;
import org.apache.ibatis.type.*;
import java.sql.*;

public abstract class BaseEnumTypeHandler<E extends Enum<? extends BaseEnum>> extends BaseTypeHandler<E>
{
    private Map<Integer, E> map;
    
    public BaseEnumTypeHandler() {
        this.map = new HashMap<Integer, E>();
        final Class<E> entityClass = (Class<E>)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        final E[] enums = entityClass.getEnumConstants();
        if (enums == null) {
            throw new IllegalArgumentException(entityClass.getSimpleName() + " does not represent an enum type.");
        }
        for (final E e : enums) {
            final BaseEnum BaseEnum = (BaseEnum)e;
            this.map.put(BaseEnum.getCode(), e);
        }
    }
    
    public void setNonNullParameter(final PreparedStatement ps, final int i, final E parameter, final JdbcType jdbcType) throws SQLException {
        ps.setInt(i, ((BaseEnum)parameter).getCode());
    }
    
    public E getNullableResult(final ResultSet rs, final String columnName) throws SQLException {
        final int id = rs.getInt(columnName);
        if (rs.wasNull()) {
            return null;
        }
        return this.map.get(id);
    }
    
    public E getNullableResult(final ResultSet rs, final int columnIndex) throws SQLException {
        final int id = rs.getInt(columnIndex);
        if (rs.wasNull()) {
            return null;
        }
        return this.map.get(id);
    }
    
    public E getNullableResult(final CallableStatement cs, final int columnIndex) throws SQLException {
        final int id = cs.getInt(columnIndex);
        if (cs.wasNull()) {
            return null;
        }
        return this.map.get(id);
    }
}
